<?php


namespace app\app\controller\user;


use app\model\DeptModel;
use app\model\UserModel;
use support\Request;
use Webman\Http\Response;

class Info
{
    protected $user_id = 0;
    protected $access_token = '';

    public function beforeAction(Request $request){
        $this->user_id = $request->user_id;
        $this->access_token = $request->access_token;
    }

    public function get(){
        $userModel = new UserModel();
        $deptModel = new DeptModel();
        $user = $userModel->info($this->user_id);
        if($user instanceof Response){
            return $user;
        }
        else{
            $user['access_token'] = $this->access_token;
            $user['full_dept'] = $deptModel->getAllDept($user['dept_id'],' - ',[]);
            return success($user);
        }
    }

    public function edt(){
        $userModel = new userModel();
        $_user = json_decode(input('info'),true);
        unset($_user['access_token']);
        $res = $userModel::update($_user);
        return $res ? success(null,0,"修改成功") : error(1,"修改失败");
    }

    public function set(){
        $userModel = new userModel();

        if(empty(input('field',null))){
            return error(1,'field is null');
        }
        if(input('field')=='sex'){
            if(!is_numeric(input('val',null))){
                return error(1,'val is null');
            }
        }
        else{
            if(empty(input('val',null))){
                return error(1,'val is null');
            }
        }


        $where[] = ['user_id','=',$this->user_id];
        $res = $userModel->where($where)->update([input('field')=>input('val')]);
        return $res ? success(null,0,"修改成功") : error(1,"修改失败");
    }

    public function setPwd(){
        $userModel = new userModel();
        $userInfo = $userModel::find($this->user_id);
        if($userInfo['password']!=md5(input('oldPsw'))){
            return error(1,"旧密码错误");
        }
        $where[]=['user_id','=',$this->user_id];
        $res = $userModel->where($where)->update(['password'=>md5(input('newPsw'))]);
        return $res ? success(null,0,"密码修改成功") : error(1,"密码修改失败");
    }

}